<?php

namespace App\Service\Message\v1_2_1;

use App\Constants\ErrorCode;
// use App\Helpers\Helper;
use App\Helpers\ImUtil;
use App\Helpers\RedisUtil;
// use App\Job\ChatInfoJob;
use App\Model\CloseFriend;
use App\Model\GiftLog;
use App\Model\Message;
use App\Model\Service\CacheService;
use App\Model\Setting\SettingUserLevel;
use App\Model\User;
use App\Model\UserBlacklist;
use App\Model\UserProfile;
use App\Model\VideoCall;
use App\Model\VoiceCall;
use App\Service\BaseService;

/**
 * 聊天框信息
 */
class ChatInfoService extends BaseService
{
    protected function RoVerifyList()
    {
        return [
            'chat_im_account' => 'required|string'
        ];
    }

    public function handle()
    {
        $userId = $this->userId;
        $user = $this->getUser();
        $chatImAccount = $this->request->input('chat_im_account', '');
        $userIds = User::getUserIdByIm($chatImAccount, 'id');
        $chatUserId = $userIds[0] ?? 0;
        if (!$chatUserId || !$userId || $chatUserId == $userId) {
            return $this->setError(ErrorCode::USER_NOT_VALID, '参数传入有误~');
        }
        //是否与小助手对话
        $isOfficialChat = User::checkOfficial([$chatUserId, $userId]);
        //双方资料
        $profiles = UserProfile::getUsersProfileObj([$userId, $chatUserId]);
        //聊友用户信息
        $chatProfile = $profiles[$chatUserId];
        //自己信息
        $selfProfile = $profiles[$userId];
        $ret['is_host'] = UserProfile::checkRoleHost($selfProfile->role);
        $ret['chat_user_id'] = $chatUserId;
        $ret['user_info'] = [
            'user_id' => $chatUserId,
            'nick_name' => $chatProfile->nick_name,
            'avatar' => UserProfile::buildAvatar($chatProfile->avatar),
            'city' => $chatProfile->city,
            'age' => $chatProfile->age,
            'level' => SettingUserLevel::getUserLevel($chatProfile),
            'tags' => [],
            'followed' => 0,
        ];

        //亲密度
        $ret['close_value'] = CloseFriend::getCloseValue($userId, $chatUserId);
        $ret['max_close_value'] = 100;
        //是否被对方拉黑
        $ret['is_blocked'] = UserBlacklist::check($chatUserId, $userId) ? 1 : 0;
        //是否拉黑对方
        $ret['is_blocking'] = UserBlacklist::check($userId, $chatUserId) ? 1 : 0;
        //是否展示语聊按钮
        $ret['can_call'] = 1;
        //是否视频按钮
        $ret['can_video'] = 1;
        //是否显示名片
        $ret['show_card'] = 1;

        //新版本的功能权限（1.2.2新版本）
        $this->packFunctions($ret, $selfProfile, $isOfficialChat);

        //小助手消息回复
        $this->officialFeedBack($user->im_account, $chatImAccount);

        //官方小助手
        if ($isOfficialChat) return $ret;

        //声优无限制
        $ret['chat_charge'] = 1;
        if ($ret['is_host']) {
            //礼物过期提示
            $ret['exp_num'] = GiftLog::expireRecords($chatUserId, $userId);
            if ($ret['exp_num'] > 0) {
                ImUtil::sendInfoTipMsg($user->im_account, '您没有及时回复消息，之前的部分礼物已被退回～', $chatImAccount);
            }
        }
        // 资料卡
        $this->doSendProfileCard($userId, $chatUserId, $chatProfile, $selfProfile, $ret);

        //真人认证提示
        $this->sendVerifyTip($userId, $chatUserId, $chatProfile, $selfProfile, $isOfficialChat);

        //用户标签
        $this->packUserTag($ret, $userId,  $chatUserId, $isOfficialChat);

        //亲密度视频
        $this->packPopHostCall($ret, $chatUserId);

        //顶部提示
        $ret['top_tip'] = [
            'text' => '请文明交流，涉及欺诈，涉黄等违规行为将会被封号处理',
            'link' => ''
        ];
        //日志
        log_user_result($userId, $chatProfile->user_id);
        return $ret;
    }

    /**
     * 发送名片卡
     */
    function doSendProfileCard(
        $userId = 0,
        $chatUserId = 0,
        $chatProfile = null,
        $selfProfile = null,
        &$ret = []
    ) {
        if (
            !$selfProfile
            || !$chatProfile
            || $selfProfile->gender == -1
            || $selfProfile->gender == $chatProfile->gender
            || $ret['is_blocked']
        ) return 0;

        //屏蔽弹窗
        if (in_array($this->appId, explode(',', env('SHOW_POP_FORBID_APPID', '6')))) return 0;

        $key = "chat_show_card_{$userId}_{$chatUserId}";
        if (RedisUtil::get($key) == 1) return 0;
        RedisUtil::set($key, 1, 3600 * 24);
        Message::sendNewProfileCard($userId, $chatUserId, $chatProfile);
        return;
    }

    /**
     * 真人认证提示
     */
    function sendVerifyTip(
        $userId = 0,
        $chatUserId = 0,
        $chatProfile = null,
        $selfProfile = null,
        $isOfficialChat = 0
    ) {
        if (
            $this->curVersion < '1.2.7'
            || !$selfProfile
            || !$chatProfile
            || $selfProfile->gender == -1
            || $selfProfile->gender == $chatProfile->gender
            || $isOfficialChat
        ) return false;

        $vryOk = UserProfile::checkAvatarVrfied($chatUserId, $chatProfile);
        if (!$vryOk) return;
        $key = "verify_tip_{$userId}_{$chatUserId}";
        if (RedisUtil::get($key) == 1) return;
        RedisUtil::set($key, 1, 3600 * 72);
        Message::sendVryOKTip($userId, $chatUserId);
    }

    /**
     * 亲密度视频
     */
    function packPopHostCall(&$ret = [], $chatUserId = 0)
    {
        $ret['pop_host_call'] = $ret['close_value'] >= 0.1 && $ret['is_host'] ? [
            'title' => '视频通话',
            'text' => '恭喜你们亲密值达到0.1度，解锁了拨打视频/语音通话功能，快跟他视频聊聊吧～
*视频邀请男方同意后需要根据你设定的通话费用进行付费哦～',
            'button_text' => '马上邀请他通话',
            'user_id' => $chatUserId,
        ] : null;
        return;
    }

    /**
     * 小助手消息回复
     */
    function officialFeedBack($fromImAccount = '', $toImAccount = '')
    {
        $officialAccount = env('IM_ACCOUNT_KEFU', '');
        if ($toImAccount != $officialAccount) return false;
        $key = "Official_auto_{$fromImAccount}";
        $lockTime = check_dev_env() ? 30 : 3600;
        if (RedisUtil::concurrentLock($key, $lockTime)) return false;
        $msg = '您好，我是客服小助手，很高兴为您服务，请您描述您想要咨询的相关问题。';
        ImUtil::sendTextMsg($fromImAccount, $msg, $officialAccount);
    }

    /**
     * 新功能入口
     */
    function packFunctions(&$ret = [], $selfProfile = null, $isOfficialChat = 0)
    {
        if ($this->curVersion < '1.2.2' || $isOfficialChat) return false;
        $lockInfo = CloseFriend::checkLock($ret['close_value']);
        if ($selfProfile->gender == 1) $lockInfo['voice_call'] = $lockInfo['video_call'] = 0;
        $ret = array_merge($ret, [
            'functions' => [
                ['type' => 'voice_call', 'show' => 1, 'locked' => $lockInfo['voice_call'], 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('voice_call')],
                ['type' => 'video_call', 'show' => 1, 'locked' => $lockInfo['video_call'], 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('video_call')],
                ['type' => 'image', 'show' => 1, 'locked' => 0, 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('image')],
                ['type' => 'video', 'show' => 1, 'locked' => $lockInfo['video'], 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('video')],
            ]
        ]);
    }

    /**
     * 标签
     */
    function packUserTag(&$ret = [], $userId = 0,  $chatUserId, $isOfficialChat = 0)
    {
        // return;
        if ($this->curVersion < '1.2.7' || $isOfficialChat) return;
        $ret['user_info']['user_tag'] = [];
        //视频过
        $videoCalled = CacheService::getCalledUsers($userId, VideoCall::CALL_TYPE);
        if (in_array($chatUserId, $videoCalled)) {
            return $ret['user_info']['user_tag'][] = Message::MSG_TAG[1]['tag_name'];
        }
        //语音过
        $voiceCalled = CacheService::getCalledUsers($userId, VoiceCall::CALL_TYPE);
        if (in_array($chatUserId, $voiceCalled)) {
            return $ret['user_info']['user_tag'][] = Message::MSG_TAG[3]['tag_name'];
        }
        //互动过
        $chatUsers = CacheService::getChatedUsers($userId);
        if (in_array($chatUserId, $chatUsers)) {
            return $ret['user_info']['user_tag'][] = Message::MSG_TAG[2]['tag_name'];
        }
    }
}
